﻿using System;
using System.Collections.Generic;
using System.Text;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.DAL;
using System.Data;

namespace HZ.DrugTrade.BLL
{
    [Serializable]
    /// <summary>
    /// 操作业务逻辑类,实现接口IBLL_SelectArea,继承自类MarshalByRefObject
    /// </summary>
    public class BLL_SelectRelation : MarshalByRefObject, IBLL_SelectRelation
    {


         /// <summary>
        /// 是否可删除可配送（尚未开始采购）
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public bool CheckCanDelRelation(string UserID)
        {
            return DAL.DAL_SelectRelation.CheckCanDelRelation(UserID);

        }
        /// <summary>
        /// 根据采购目录编号获取配送信息
        /// </summary>
        /// <param name="ProcureCatalogID">采购目录编号</param>
        /// <returns>配送信息</returns>
        public IList<SelectRelation> GetAllSelectRelation(string ProcureCatalogID)
        {
            int totalRecord = 0;
            SelectRelation sarea = new SelectRelation()
            {
                ProcureCatalogID = ProcureCatalogID
            };
            return DAL.DAL_SelectRelation.GetSelectRelationByWhere(sarea, 1, 0, out totalRecord);
        }

        /// <summary>
        /// 获取条数
        /// </summary>
        /// <returns></returns>
        public int GetSelectRelationCount()
        {
            return DAL_SelectRelation.GetSelectRelationCount();
        }

        /// <summary>
        /// 根据配送企业编号获取配送信息
        /// </summary>
        /// <param name="ProcureCatalogID">配送企业编号</param>
        /// <returns>配送信息</returns>
        public IList<SelectRelation> GetAllSelectRelationByCompanyPSID(string CompanyID_PS)
        {
            int totalRecord = 0;
            SelectRelation sarea = new SelectRelation()
            {
                CompanyID_PS = CompanyID_PS
            };
            return DAL.DAL_SelectRelation.GetSelectRelationByWhere(sarea, 1, 0, out totalRecord);
        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int AddSelectRelation(HZ.DrugTrade.Model.SelectRelation selectRelation, string ProjectID)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.AddSelectRelation(selectRelation,ProjectID);
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        public int AddSelectRelation(IList<Model.SelectRelation> lst, object ishcygcg, out int[] arrayResult)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.AddSelectRelation(lst, ishcygcg, out arrayResult);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int UpdateSelectRelation(HZ.DrugTrade.Model.SelectRelation selectRelation)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.UpdateSelectRelation(selectRelation);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int UpdateSelectRelation(IList<Model.SelectRelation> lst)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.UpdateSelectRelation(lst);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int UpdateSelectRelation(string strCompanyID_TB)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.UpdateSelectRelation(strCompanyID_TB);
        }
        /// <summary>
        /// 更新:更新可配送状态
        /// </summary>
        /// <param name="strCompanyID_TB"></param>
        /// <returns></returns>
        public int UpdateSelectRelation(string strCompanyID_TB, int status)
        {
            BLL_UserSession.CheckSession();
            int state = DAL.DAL_SelectRelation.UpdateSelectRelation(strCompanyID_TB, status);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("更新可配送状态：{0};处理时间:{1};)", strCompanyID_TB, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 删除企业的配送关系
        /// </summary>
        /// <param name="selectRelation">配送关系模型</param>
        /// <returns>返回值 0：删除出错 1 删除成功 2 医疗机构已经选择</returns>
        public int DeleteSelectRelation(HZ.DrugTrade.Model.SelectRelation selectRelation)
        {
            BLL_UserSession.CheckSession();
            int state = DAL.DAL_SelectRelation.DeleteSelectRelation(selectRelation);
            if(state ==1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("删除企业的配送关系：{0};处理时间:{1};)", selectRelation.CompanyID_PS, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int DeleteSelectRelationByAdmin(HZ.DrugTrade.Model.SelectRelation selectRelation)
        {
            BLL_UserSession.CheckSession();
            var h = HZ.Data.DbHelperFactory.Create(); 
            try
            {
                h.BeginTrans();


                string strSql = string.Format(@"delete  TB_SelectRelation
 WHERE CompanyID_PS = '{0}' and ProcureCatalogID='{1}' and AreaID='{2}'", selectRelation.CompanyID_PS, selectRelation.ProcureCatalogID, selectRelation.AreaID);

                h.ExecuteNonQuery(strSql);

                string strSql2 = string.Format(@"DELETE FROM TB_AreaDistribution
 WHERE CompanyID_PS = '{0}' and ProcureCatalogID='{1}' and AreaID='{2}'", selectRelation.CompanyID_PS, selectRelation.ProcureCatalogID, selectRelation.AreaID);

                h.ExecuteNonQuery(strSql2);

                //置空该地区与该配送企业存在配送关系的信息
                string strSql3 = string.Format(@"UPDATE TB_HospitalProcureCatalog
   SET CompanyID_PS=null,CompanyName_PS=null
 WHERE ProcureCatalogID ='{0}' and CompanyID_PS ='{1}' and HospitalID in (SELECT HospitalID
  FROM TB_HospitalInfo
where AreaID like '{2}%')", selectRelation.ProcureCatalogID, selectRelation.CompanyID_PS, selectRelation.AreaID.Substring(0,4));

                h.ExecuteNonQuery(strSql3);

                //修改配送关系的日志
                BLL_Log.Instance.AddKeyOperationLog(new HZ.DrugTrade.Model.KeyOperationLog() { OperateMessage = string.Format("操作人：{0};操作时间:{1};操作内容:" + strSql + ";" + strSql2 + ";" + strSql3, selectRelation.Auditer,DateTime.Now.ToString()) });

                h.CommitTrans();
                return 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DeleteSelectRelationByAdmin", ee.Message, ee);
                return 0;
            }
        }
        /// <summary>
        /// 配送关系
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetSelectRelationByProcureCatalogID(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            //去除视图索引
            sql.Append(string.Format(@"SELECT *  FROM View_SelectRelation  where 1=1 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }


        /// <summary>
        /// 配送关系确认
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetSelectRelationToConfirm(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            BLL_UserSession.CheckSession();
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT * FROM View_SelectRelationConfirm  where 1=1 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }
        /// <summary>
        /// 配送关系确认
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetSelectRelationToConfirm2(string strWhere, int currentPage, int pageSize, out int totalRecord)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format(@"SELECT * FROM View_SelectRelationConfirm   where 1=1 {0} ", strWhere));
            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql.ToString(), pageSize);
            des.CurrentPage = currentPage;
            totalRecord = des.TotalCount;
            return des.GetSpecailPage();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strCompanyID"></param>
        /// <returns></returns>
        public int UpdateCompanyInfoCheckStatus(string strCompanyID,int checkstatus,bool temp)
        {
            BLL_UserSession.CheckSession();
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                string strSql = string.Empty;
                string strSql2 = string.Empty;
                string strSql3 = string.Empty;
                //将所有未审核企业审核通过
                if (temp && string.IsNullOrEmpty(strCompanyID))
                {
                    strSql = string.Format(@"UPDATE TB_CompanyInfo SET CheckStatus =1  WHERE CheckStatus=0");

                    h.ExecuteNonQuery(strSql);
                }
                else if (checkstatus == 1)
                {
                    strSql2 = string.Format(@"UPDATE TB_CompanyInfo SET CheckStatus =1  WHERE CompanyID = '{0}'", strCompanyID);

                    h.ExecuteNonQuery(strSql2);
                }
                else if (checkstatus == 2)
                {
                    strSql2 = string.Format(@"UPDATE TB_CompanyInfo SET CheckStatus =2  WHERE CompanyID = '{0}'", strCompanyID);

                    h.ExecuteNonQuery(strSql2);

                    //清理配送关系

                    //置空该地区与该配送企业存在配送关系的信息
                    strSql3 = string.Format(@"UPDATE TB_HospitalProcureCatalog
   SET CompanyID_PS=null,CompanyName_PS=null
 WHERE CompanyID_PS ='{0}';", strCompanyID);
                    //清除该配送企业的可配送区域信息
                    strSql3 += string.Format(@"DELETE TB_AreaDistribution
 WHERE CompanyID_PS ='{0}';", strCompanyID);

                    //清除该配送企业的可配送区域信息2
                    strSql3 += string.Format(@"DELETE TB_SelectRelation
 WHERE CompanyID_PS ='{0}';", strCompanyID);
                    //置空该配送企业的可配送区域信息2
                    strSql3 += string.Format(@"UPDATE TB_SelectArea
   SET AreaIDs=null
 WHERE CompanyID_PS ='{0}';", strCompanyID);

                    //取消该企业的可配送区域管理权限
                    strSql3 += string.Format(@"delete from  TB_UserRule
 WHERE UserID like '{0}%' and OperatingRuleID='166';", strCompanyID);

                    h.ExecuteNonQuery("BEGIN  "+strSql3+" END;");
                }


                //修改配送关系的日志
                BLL_Log.Instance.AddKeyOperationLog(new HZ.DrugTrade.Model.KeyOperationLog() { OperateMessage = string.Format(strSql + ";" + strSql2 + ";" + strSql3) });

                h.CommitTrans();
                return 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DeleteSelectRelationByAdmin", ee.Message, ee);
                return 0;
            }
        }



        /// <summary>
        /// 统计
        /// </summary>
        /// <returns></returns>
        public DataTable GetAreaDistribution()
        {
            return DAL.DAL_SelectRelation.GetAreaDistribution();
        }

        /// <summary>
        /// 检查
        /// </summary>
        /// <returns></returns>
        public DataTable GetEspeciallyRelationShip()
        {
            return DAL.DAL_SelectRelation.GetEspeciallyRelationShip();
        }

        /// <summary>
        /// 更新:校正查因COOKIE导致的异常数据
        /// </summary>
        /// <returns></returns>
        public int UpdateEspeciallyRelationShip()
        {
            return DAL.DAL_SelectRelation.UpdateEspeciallyRelationShip();
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="selectRelation"></param>
        /// <returns></returns>
        public int UpdateSelectRelationAuditStatus(IList<Model.SelectRelation> lst)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.UpdateSelectRelationAuditStatus(lst);
        }

        /// <summary>
        /// 据配送企业得到生产企业的id
        /// </summary>
        /// <param name="cmpPSId"></param>
        /// <returns></returns>
        public string GetCmpSCByCmpPSId(string cmpPSId)
        {
            BLL_UserSession.CheckSession();
            return DAL.DAL_SelectRelation.GetCmpSCByCmpPSId(cmpPSId);
        }
        /// <summary>
        /// 企业提交申请删除配送关系
        /// add by Meng 2013-04-10
        /// </summary>
        /// <param name="srelation"></param>
        /// <returns></returns>
        public int GetDelRequestDelete(HZ.DrugTrade.Model.SelectRelation srelation)
        {
            BLL_UserSession.CheckSession();
            int state =  DAL.DAL_SelectRelation.GetDelRequestDelete(srelation);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("企业提交申请删除配送关系：{0};处理时间:{1};)", srelation.CompanyID_PS, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
    }
}

